%% ---
-module(knowledge_commons).
-import(lists, [foreach/2]).
-compile(export_all).

-include_lib("stdlib/include/qlc.hrl").

-record(objects, {id, string}).
-record(relations, {id, object_id, source_id, target_id}).

do_this_once() ->
    mnesia:create_schema([node()]),
    mnesia:start(),
    mnesia:create_table(objects, [{attributes, record_info(fields, objects)}]),
    mnesia:create_table(relations, [{attributes, record_info(fields, relations)}]),
    mnesia:stop().


start() ->
    mnesia:start(),
    mnesia:wait_for_tables([objects,relations], 20000).

show_objects() ->    
    F = fun() -> 
	qlc:e(qlc:q([X || X <- mnesia:table(objects)])) 
    end,
    {atomic, Val} = mnesia:transaction(F),
    Val.

show_relations() ->    
    F = fun() -> 
	qlc:e(qlc:q([X || X <- mnesia:table(relations)])) 
    end,
    {atomic, Val} = mnesia:transaction(F),
    Val.

show_relations_join() ->
    F = fun() -> 
	qlc:e(qlc:q([X#objects.string || X <- mnesia:table(objects),
					 Y <- mnesia:table(relations),
					 X#objects.id =:= Y#relations.object_id
						]))
    end,
    {atomic, Val} = mnesia:transaction(F),
    Val.
   


add_object(Id,String) ->

    Row = #objects{id =Id, string=String},

    F = fun() ->
		mnesia:write(Row)
	end,
    mnesia:transaction(F).

add_relations(Id,Oid,Sid,Tid) ->

    Row = #relations{id =Id, object_id = Oid, source_id = Sid, target_id = Tid},

    F = fun() ->
		mnesia:write(Row)
	end,
    mnesia:transaction(F).



